package cn.zhy.org.controller;


import cn.zhy.basic.util.AjaxResult;
import cn.zhy.basic.util.PageList;
import cn.zhy.org.domain.Department;
import cn.zhy.org.query.DepartmentQuery;
import cn.zhy.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService DepartmentService;

    //查询一条记录
    @GetMapping("/{id}")
    public Department loadById(@PathVariable("id") Long id){
            return DepartmentService.loadById(id);
    }
    //查询全部记录
    @GetMapping()
    public List<Department> loadAll(){
        return DepartmentService.loadAll();
    }


    //分页查询+高级查询
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){

        return DepartmentService.queryPage(departmentQuery);

    }
    //删除一条记录
    @DeleteMapping("/{id}")
    public AjaxResult removeById(@PathVariable("id") Long id){

        try {
            DepartmentService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
           // return AjaxResult.me().setSuccess(false).setMessage("错误");n
            return new AjaxResult(false,"操作失败");
        }

    };

    //添加或者修改记录
    @PutMapping()
    public AjaxResult addOrUpdate(@RequestBody Department department){

        try {
            if (department.getId() !=null) {
                DepartmentService.update(department);
            }else {
                DepartmentService.save(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("错误");
        }

    };

    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            System.out.println(ids);
            DepartmentService.patchDelete(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除批量失败");
        }
    }

    /**
     *查询部门树
     */
    @GetMapping("/deptTree")
    public List<Department> deptTree(){
        return DepartmentService.deptTree();
    }

}
